

package jetbrains.buildServer.server.rest.model.user;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import jetbrains.buildServer.server.rest.model.Fields;
import jetbrains.buildServer.server.rest.model.project.Project;
import jetbrains.buildServer.server.rest.swagger.annotations.ModelDescription;
import jetbrains.buildServer.server.rest.util.BeanContext;
import jetbrains.buildServer.server.rest.util.ValueWithDefault;
import jetbrains.buildServer.serverSide.SProject;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@XmlRootElement(name = "permissionRestriction")
@XmlType(name = "permissionRestriction")
@ModelDescription("Represents permission restrictions of an authentication token.")
public class PermissionRestriction {
  @Nullable
  @XmlAttribute
  public Boolean isGlobalScope;
  @Nullable
  @XmlElement
  public Project project;
  @Nullable
  @XmlElement
  public Permission permission;

  public PermissionRestriction() {
  }

  public PermissionRestriction(@Nullable final SProject project,
                               @NotNull final jetbrains.buildServer.serverSide.auth.Permission permission,
                               @NotNull final Fields fields,
                               @NotNull final BeanContext beanContext) {
    this.isGlobalScope = ValueWithDefault.decideIncludeByDefault(fields.isIncluded("isGlobalScope", true, true), () -> project == null);
    this.project =
      ValueWithDefault.decideDefault(fields.isIncluded("project", false, true), () -> project != null ? new Project(project, fields.getNestedField("project"), beanContext) : null);
    this.permission = ValueWithDefault.decideIncludeByDefault(
      fields.isIncluded("permission", true, true),
      () -> new Permission(permission, fields.getNestedField("permission"))
    );
  }
}